package org.dbstar.scheduler.job;

import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dbstar.scheduler.beans.CmdJob;
import org.dbstar.scheduler.beans.CmdJobConf;
import org.dbstar.scheduler.beans.JobConf;
import org.dbstar.scheduler.utils.JobUtils;


/**
 * 构建CmdJob
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-4-28
 */
public class CmdJobFactory extends AbstractJobFactory<CmdJob> {
	@Override
	public CmdJob createJob(SchedulerFactory schedulerFactory, JobConf conf, String submitter,
			Map<String, String> parameters, long submitTime) throws IllegalFactoryException {
		if (conf == null) {
			throw new IllegalFactoryException("Job Conf is null");
		}
		if (StringUtils.isBlank(submitter)) {
			throw new IllegalFactoryException("Job Submitter is null");
		}
		CmdJob job = new CmdJob();
		job.setJobConfIdentifier(conf.getIdentifier());
		job.setSubmitTime(submitTime);
		job.setParameters(JobUtils.getJobParameters(conf, parameters, true));
		job.setMaxRetry(conf.getMaxRetry());
		job.setSubmitter(submitter);

		// 设置命令行
		String cmd = ((CmdJobConf) conf).getCmd();
		if (job.getParameterSize() > 0) {
			cmd = JobUtils.formatByParameter(cmd, job.getParameters());
		}
		cmd = cmd.replaceAll("\r", "").replaceAll("\\\\n", "\n");
		job.setFinalCmd(cmd);

		// 设置资源
		String resource = conf.getResource();
		if (resource != null) {
			resource = JobUtils.formatByParameter(resource, job.getParameters());
			int index = resource.indexOf("@");
			if (index >= 0) {
				resource = resource.substring(index + 1);
			}
		}
		job.setResource(resource);

		return job;
	}
}
